<?php
namespace control;

/*
*绩效规则类
*/

class performanceRuleClass extends adIndexClass
{
    private const page = 'performanceRule';
    private const table = 'performance_rule';
    private const title = '绩效规则';

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            select(array("name" => "team", "title" => L('performance.table.team'), "option" => explode('，', para('performanceTeam')))) .
            text(array("name" => "createTime", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('performance.table.updateTime') . "-" . L('performance.table.updateTime')));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array();
        //全等查询数组
        $equal = array(
            "team" => $this->post('team'),//绩效组
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'updateTime');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "updateTime desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('performance.table.team'), L('performance.table.scoreStart'), L('performance.table.scoreEnd'), L('performance.table.rate'), L('performance.table.updateTime'));
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('performance.table.info'), "click" => "newIframe('" . L('performance.table.info') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $tr[] = array($this->dominate($dominate), $array['team'], $array['minScore'], $array['maxScore'], $array['ratio'], $array['updateTime']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('performance.table.info') . "','" . $url . "&fun=edit')\" class='spanButton'>" . L('job.model.edit') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('job.button.delete') . "</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    must . L('performance.table.team') . "：" => select(array('name' => 'team', 'title' => L('performance.table.team'), 'class' => 'select', 'value' => $info['team'], 'option' => explode('，', para('performanceTeam')))),
                ],
                [
                    must . L('performance.table.score_range') . "：" => text(array('name' => 'minScore', 'class' => 'text', 'value' => $info['minScore'])) . "<span><=" . L('staffProfiles.detail.score') . "<</span>" . text(array('name' => 'maxScore', 'class' => 'text', 'value' => $info['maxScore'])),
                ],
                [
                    must . L('performance.table.rate') . "：" => text(array('name' => 'ratio', 'class' => 'text', 'value' => $info['ratio'])),
                ],
                [
                    L('staffProfiles.table.text') . "：" => textarea(array('name' => 'text', 'class' => 'textarea', 'value' => $info['text'])),
                ],
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $info['id'] ?: $id)),
            'button' => "<button class=\"button left-bottom\" onclick=\"subForm('{$this->get('cla')}EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')\">" . L('recruitment.table.commit') . "</button>",
        ]);
        //返回
        return $this->tab($data);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'team' => $this->post('team'),
            'minScore' => $this->post('minScore'),
            'maxScore' => $this->post('maxScore'),
            'ratio' => $this->post('ratio'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'team' => L('performance.table.team'),
            'minScore' => L('performance.table.score_range'),
            'maxScore' => L('performance.table.score_range'),
            'ratio' => L('performance.table.rate'),
        ];
        $rules = [
            'team' => 'required',
            'ratio' => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('performance.table.rule_edit_permission');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'JX',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{team}}', '{{id}}'], [$this->control['name'], $field['team'], $id], L('performance.table.rule_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('performance.table.find_none_rule');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($this->power(self::page, "edit")) {

                //按钮
                $button[] = [
                    "name" => L('department.button.delete'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                //按钮
                $button[] = [
                    "name" => L('job.button.editor'),
                    "type" => "顶部页卡",
                    "title" =>L('job.button.editor'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
            }

            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                array(
                    array(
                        L('performance.table.team') => $info['team'],
                        L('performance.table.score_range')=> $info['minScore'] . '<='.L('staffProfiles.detail.score').'<' . $info['maxScore'],
                        L('performance.table.rate') => $info['ratio'],
                    ),
                    array(
                        L('staffProfiles.table.text') => $info['text'],
                    ),
                ),
                L('staffProfiles.detail.system_info') => array(

                    array(
                        L('performance.table.orderNo') => $info['orderNo'],
                        L('department.table.creator') => self::findStaff($info['stid']),
                        L('department.table.creatTime') => $info['time'],
                    ),
                    array(
                        L('department.table.updateTime') => $info['updateTime'],
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('performance.table.del_rule');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'],[$msg],L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] =  L('staffProfiles.tip.permission_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = L('job.other.delete_success');
                $x++;
                $text .= str_replace(['{{team}}','{{start}}','{{end}}','{{id}}'],[$info['team'],$info['minScore'],$info['maxScore'],$info['id']],L('performance.table.rule_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('performance.table.rule_del_log')). "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('performance.table.rule_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

